package com.wtwd.campus.jdzc.controller;

import com.wtwd.campus.common.Constants;
import com.wtwd.campus.entity.DeviceSetting;
import com.wtwd.campus.entity.SilentShutdownVo;
import com.wtwd.campus.entity.WxLocateModeVO;
import com.wtwd.campus.entity.WxSleepModeVO;
import com.wtwd.campus.jdzc.common.Constant;
import com.wtwd.campus.jdzc.common.RespCode;
import com.wtwd.campus.jdzc.common.RespEntity;
import com.wtwd.campus.jdzc.dao.JdzcDeviceSettingMapper;
import com.wtwd.campus.jdzc.entity.DeviceInfo;
import com.wtwd.campus.jdzc.service.AuthService;
import com.wtwd.campus.jdzc.service.JdzcDeviceInfoService;
import com.wtwd.campus.jdzc.service.JdzcUserStudentPermissionService;
import com.wtwd.campus.service.RedisService;
import com.wtwd.campus.utils.CommandSendUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ldaoliang
 * @DateTime: 2022/2/14 16:29
 * @Description: 模式设置
 */
@RestController
@RequestMapping("/jdzc/model")
public class JdzcDeviceSettingController {

    private static final Logger logger = LoggerFactory.getLogger(JdzcDeviceSettingController.class);


    @Autowired
    private JdzcDeviceInfoService deviceInfoService;

    @Autowired
    private AuthService authService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private JdzcUserStudentPermissionService jdzcUserStudentPermissionService;

    @Autowired
    private CommandSendUtils commandSendUtils;

    @Autowired
    private JdzcDeviceSettingMapper jdzcDeviceSettingMapper;

    /**
     * 获取设置页各模式的设置状态
     */
    @GetMapping("/getModeStatus/{stuId}")
    public RespEntity getModeStatus(@PathVariable("stuId") Integer stuId, HttpServletRequest request) {
        logger.info("/getModeStatus : stuId = {} ", stuId.toString());
        Integer userId = getUserId(request);
        //校验学生
        Boolean authStudent = authService.authStudent(stuId, Constant.jdzcOrgCode, userId);
        if (!authStudent) {
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        //根据学生id获取设备信息
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(stuId);
        if (deviceInfo == null) {
            return new RespEntity(RespCode.STUDENT_NOT_BIND_DEVICE);
        }
        //获取各模式的状态
        Map<String, Object> map = deviceInfoService.getModeStatusByDeviceId(deviceInfo.getDeviceId(), deviceInfo.getImei());
        /* map.put("locateMode", deviceInfo.getWorkingPattern() == null ? Constants.DEFAULT_WORK_PATTERN : deviceInfo.getWorkingPattern());*/
        return new RespEntity(RespCode.SUCCESS, map);
    }

    /**
     * 获取定位模式的信息
     */
    @GetMapping("/getLocateModeMess/{stuId}")
    public RespEntity getLocateModeMess(@PathVariable("stuId") Integer stuId, HttpServletRequest request) {
        logger.info("/getLocateModeMess : stuId = {} ", stuId.toString());
        Integer userId = getUserId(request);
        //校验学生
        Boolean authStudent = authService.authStudent(stuId, Constant.jdzcOrgCode, userId);
        if (!authStudent) {
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        //根据学生id获取设备信息
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(stuId);
        if (deviceInfo == null) {
            return new RespEntity(RespCode.STUDENT_NOT_BIND_DEVICE);
        }
        //获取设备的定位模式信息
        Map<String, Object> result = new HashMap<>();
        if (deviceInfo.getWorkingPattern() == null) {
            result.put("realTimeMode", Constants.UP_INTERVAL);
            result.put("powerSaveMode", Constants.POWER_SAVING_MODEL_UP_INTERVAL);
            result.put("type", Constants.DEFAULT_WORK_PATTERN);
        } else if (deviceInfo.getWorkingPattern() == Constants.DEFAULT_WORK_PATTERN) {
            result.put("realTimeMode", deviceInfo.getUpInterval());
            result.put("powerSaveMode", Constants.POWER_SAVING_MODEL_UP_INTERVAL);
            result.put("type", Constants.DEFAULT_WORK_PATTERN);
        } else if (deviceInfo.getWorkingPattern() == Constants.POWER_SAVING_MODEL) {
            result.put("realTimeMode", Constants.UP_INTERVAL);
            result.put("powerSaveMode", deviceInfo.getUpInterval());
            result.put("type", Constants.POWER_SAVING_MODEL);
        }
       /* result.put("mode", deviceInfo.getWorkingPattern() == null ? Constants.DEFAULT_WORK_PATTERN : deviceInfo.getWorkingPattern());
        result.put("interval", deviceInfo.getUpInterval() == null ? Constants.UP_INTERVAL : deviceInfo.getUpInterval());*/
        return new RespEntity(RespCode.SUCCESS, result);
    }


    /**
     * 设置定位模式
     *
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/setLocateMode")
    public RespEntity setLocateMode(@RequestBody WxLocateModeVO data, HttpServletRequest request) {
        //获取用户id
        logger.info("/setLocateMode : data = {} ", data.toString());
        Integer userId = getUserId(request);
        if (userId == 0) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        if (data.getStuId() == null || data.getMode() == null || data.getInterval() == null) {
            return new RespEntity(RespCode.PARAMS_ERROR);
        }
        //校验学生是否可供操作
        Boolean authStudent = authService.authStudent(data.getStuId(), Constant.jdzcOrgCode, userId);
        if (!authStudent) {
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        boolean b = veryAuthentication(data.getStuId(), userId);
        if (b) {
            //获取设备信息
            DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(data.getStuId());
            if (deviceInfo != null) {
                //判断设备是否在线
                boolean isOnline = deviceOnline(deviceInfo.getImei());
                //获取流水号
                String command = getCurTime();
                boolean b1 = commandSendUtils.setDeviceMode(deviceInfo.getImei(), command, data.getMode(), data.getInterval(), isOnline, Constants.WX_COMMAND_USER_ID, false);
                if (b1) {
                    return new RespEntity(RespCode.SUCCESS);
                }
                return new RespEntity(RespCode.FAILED);
            }
            return new RespEntity(RespCode.STUDENT_NOT_BIND_DEVICE);
        }
        return new RespEntity(RespCode.NO_RIGHT_OPERATION);
    }

    /**
     * 获取睡眠模式信息
     *
     * @param stuId
     * @param request
     * @return
     */
    @GetMapping("/getSleepModeMess/{stuId}")
    public RespEntity getSleepModeMess(@PathVariable("stuId") Integer stuId, HttpServletRequest request) {
        logger.info("/getSleepModeMess : stuId = {} ", stuId.toString());
        //获取用户id
        Integer userId = getUserId(request);
        if (userId == 0) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        //校验学生是否可供操作
        Boolean authStudent = authService.authStudent(stuId, Constant.jdzcOrgCode, userId);
        if (!authStudent) {
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        //根据学生id获取设备信息
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(stuId);
        if (deviceInfo == null) {
            return new RespEntity(RespCode.STUDENT_NOT_BIND_DEVICE);
        }
        //获取设备获取设备设置信息
        DeviceSetting setting = jdzcDeviceSettingMapper.getDeviceSettingByDeviceId(deviceInfo.getDeviceId());
        Integer sleepSwitch = setting.getSleepSwitch();
        String sleepStart = setting.getSleepStart();
        String sleepEnd = setting.getSleepEnd();
        Map<String, Object> result = new HashMap<>();
        result.put("sleepSwitch", sleepSwitch == null ? Constants.SLEEP_SWITCH_CLOSE : sleepSwitch);
        result.put("sleepStart", StringUtils.isBlank(sleepStart) ? Constants.SLEEP_DEFAULT_START : sleepStart);
        result.put("sleepEnd", StringUtils.isBlank(sleepEnd) ? Constants.SLEEP_DEFAULT_END : sleepEnd);
        return new RespEntity(RespCode.SUCCESS, result);
    }

    /**
     * 设置睡眠模式
     *
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/setSleepMode")
    public RespEntity setSleepMode(@RequestBody WxSleepModeVO data, HttpServletRequest request) {
        //获取用户id
        Integer userId = getUserId(request);
        if (userId == 0) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("/setSleepMode : data = {} ", data.toString());
        //校验学生是否可供操作
        Boolean authStudent = authService.authStudent(data.getStuId(), Constant.jdzcOrgCode, userId);
        if (!authStudent) {
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        boolean b = veryAuthentication(data.getStuId(), userId);
        if (b) {
            //获取设备信息
            DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(data.getStuId());
            if (deviceInfo != null) {
                //判断设备是否在线
                boolean isOnline = deviceOnline(deviceInfo.getImei());
                DeviceSetting setting = jdzcDeviceSettingMapper.getDeviceSettingByDeviceId(deviceInfo.getDeviceId());
                if (setting == null) {
                    return new RespEntity(RespCode.DEVICE_SETTING_NOT_EXIST);
                }
                //如果是关闭，则获取数据库中的开始结束时间
                if (data.getSwitchFlag() == Constants.SLEEP_SWITCH_CLOSE) {
                    data.setStartTime(StringUtils.isBlank(setting.getSleepStart()) ? Constants.SLEEP_DEFAULT_START : setting.getSleepStart());
                    data.setEndTime(StringUtils.isBlank(setting.getSleepEnd()) ? Constants.SLEEP_DEFAULT_END : setting.getSleepEnd());
                }
                //获取流水号
                String command = getCurTime();
                boolean b1 = commandSendUtils.setSleepTimeAutoChangeMode(deviceInfo.getImei(), command, data.getStartTime(), data.getEndTime(), data.getSwitchFlag(), isOnline, Constants.WX_COMMAND_USER_ID, false);
                if (b1) {
                    //加个判断，如果现在正处于睡眠模式中，则提示模式结束后执行指令
                    if (setting.getSleepSwitch() != null && setting.getSleepSwitch() == Constants.SLEEP_SWITCH_OPEN) {
                        boolean b2 = judgeSleepTimeReply(setting.getSleepStart(), setting.getSleepEnd());
                        if (b2) {
                            return new RespEntity(RespCode.WAIT_END_SET_SLEEP_TIME);
                        }
                    }
                    return new RespEntity(RespCode.SUCCESS);
                }
                return new RespEntity(RespCode.FAILED);
            }
            return new RespEntity(RespCode.STUDENT_NOT_BIND_DEVICE);
        }
        return new RespEntity(RespCode.NO_RIGHT_OPERATION);
    }


    /**
     * 远程重启
     *
     * @param stuId
     * @param request
     * @return
     */
    @GetMapping("/restartDevice/{stuId}")
    public RespEntity restartDevice(@PathVariable("stuId") Integer stuId, HttpServletRequest request) {
        //获取用户id
        Integer userId = getUserId(request);
        if (userId == 0) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("/restartDevice : stuId = {} ", stuId.toString());
        Boolean authStudent = authService.authStudent(stuId, Constant.jdzcOrgCode, userId);
        if (!authStudent) {
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        boolean b = veryAuthentication(stuId, userId);
        if (b) {
            //获取设备信息
            DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(stuId);
            if (deviceInfo != null) {
                //判断设备是否在线
                boolean isOnline = deviceOnline(deviceInfo.getImei());
                if (isOnline) {
                    //获取流水号
                    String command = getCurTime();
                    boolean b1 = commandSendUtils.restartDevice(deviceInfo.getImei(), command, Constants.WX_COMMAND_USER_ID);
                    if (b1) {
                        return new RespEntity(RespCode.SUCCESS);
                    }
                    return new RespEntity(RespCode.FAILED);
                }
                return new RespEntity(RespCode.DEVICE_NOT_ONLINE);
            }
            return new RespEntity(RespCode.STUDENT_NOT_BIND_DEVICE);
        }
        return new RespEntity(RespCode.NO_RIGHT_OPERATION);
    }


    /**
     * 查看设备的静默状态
     *
     * @param stuId
     * @param request
     * @return
     */
    @GetMapping("/getSilentShutDownStatus/{stuId}")
    public RespEntity getSilentShutDownStatus(@PathVariable("stuId") Integer stuId, HttpServletRequest request) {
        logger.info("/getSilentShutDownStatus : stuId = {} ", stuId.toString());
        Integer userId = getUserId(request);
        if (userId == 0) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        Boolean authStudent = authService.authStudent(stuId, Constant.jdzcOrgCode, userId);
        if (!authStudent) {
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        //根据学生id获取设备信息
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(stuId);
        if (deviceInfo == null) {
            return new RespEntity(RespCode.STUDENT_NOT_BIND_DEVICE);
        }
        //获取设备获取设备设置信息
        DeviceSetting setting = jdzcDeviceSettingMapper.getDeviceSettingByDeviceId(deviceInfo.getDeviceId());
        Map<String, Object> map = new HashMap<>();
        map.put("silentStatus", setting.getSilentShutdown() == null ? Constants.SILENT_SHUTDOWN_CLOSE : setting.getSilentShutdown());
        return new RespEntity(RespCode.SUCCESS, map);
    }


    /**
     * 设置静默关机
     *
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/setSilentShutdown")
    public RespEntity setSilentShutdown(@RequestBody SilentShutdownVo data, HttpServletRequest request) {
        //获取用户id
        Integer userId = getUserId(request);
        if (userId == 0) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("/setSilentShutdown : data = {} ", data.toString());
        Boolean authStudent = authService.authStudent(data.getStuId(), Constant.jdzcOrgCode, userId);
        if (!authStudent) {
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        boolean b = veryAuthentication(data.getStuId(), userId);
        if (b) {
            //获取设备信息
            DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(data.getStuId());
            if (deviceInfo != null) {
                //判断设备是否在线
                boolean isOnline = deviceOnline(deviceInfo.getImei());
                //获取流水号
                String command = getCurTime();
                //进行指令下发
                boolean b1 = commandSendUtils.setShutDownSilent(data.getFlagSwitch(), deviceInfo.getImei(), command, Constants.WX_COMMAND_USER_ID, isOnline, false);
                if (b1) {
                    return new RespEntity(RespCode.SUCCESS);
                }
                return new RespEntity(RespCode.FAILED);
            }
            return new RespEntity(RespCode.STUDENT_NOT_BIND_DEVICE);
        }
        return new RespEntity(RespCode.NO_RIGHT_OPERATION);
    }




    public boolean judgeSleepTimeReply(String start, String end) {
        //获取当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String now = sdf.format(new Date(System.currentTimeMillis()));
        if (end.compareTo(start) > 0) {
            //结束时间比开始时间大
            if (now.compareTo(start) > 0 && end.compareTo(now) > 0) {
                return true;
            }
            return false;
        } else {
            //结束时间比开始时间小(跨天)
            if (now.compareTo(start) > 0 && now.compareTo(end) > 0) {
                return true;
            } else if (now.compareTo(start) < 0 && now.compareTo(end) < 0) {
                return true;
            }
            return false;
        }
    }


    /**
     * 判断设备是否在线
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    public boolean deviceOnline(String imei) {
        boolean isOnline = redisService.hasKey(Constants.DEVICE_ONLINE_PREFIX + imei);
        logger.info("设备:【{}】: {}", imei, isOnline ? "在线" : "离线");
        return isOnline;
    }

    /**
     * 获取当前时间的时分秒（HHmmss）
     *
     * @return
     */
    public String getCurTime() {
        Date d = new Date();
        SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");
        String format = sbf.format(d);
        String[] split = format.split(":");
        String time = split[0].concat(split[1]).concat(split[2]);
        return time;
    }


    /**
     * 获取用户id
     *
     * @param request
     * @return
     */
    public Integer getUserId(HttpServletRequest request) {
        //获取用户id
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        if (token.equals("aaab")) {
            return 3;
        }
        String redisUserId = redisService.getValue(token);
        if (StringUtils.isBlank(redisUserId)) {
            return 0;
        }
        Integer userId = Integer.parseInt(redisUserId);
        return userId;
    }

    /**
     * 判断操作的家长是否是学生的主监护人
     *
     * @param stuId
     * @param userId
     * @return
     */
    public boolean veryAuthentication(Integer stuId, Integer userId) {
       /* //根据学生id查找学生信息
        Map<String, Object> student = studentService.getStudentByStuId(stuId);
        //根据微信用户id查询用户电话号码
        String number = deviceWhiteListService.getNumberByWXUserId(userId);
        if (number == null || !((String) student.get("parent_phone")).equals(number)) {
            return false;
        }
        return true;*/
        //根据学生id和用户id查询一条绑定记录
        Map<String, Object> map = jdzcUserStudentPermissionService.getBindingByStuIdAndUserId(stuId, userId);
        Integer isAuthorization = (Integer) map.get("is_authorization");
        if (isAuthorization == null) {
            return false;
        }
        return isAuthorization == 1 ? true : false;
    }


}
